<?php

$path = dirname(dirname(__FILE__));
require($path.'/lib/crt.php');

$crt = new CRT();
$crt->init();

$db = DBs::getGISDB();

$sql = "select max(datemodified) from crtlog";
$date = $db->GetOne($sql);

$names = Clean::string($_REQUEST['neighborhoods'], false, false, true);

if(false && $runDate > $date) {
	echo json_encode(true);
	exit;
}

if($names) {
	$names = explode(',', $names);
	foreach($names as &$n) {
		$n = $db->qstr($n);
	}

	$nameSql = " AND name1 IN (".implode(',', $names).") ";
	$sql = "DELETE FROM ".LABELS_TBL." WHERE 1=1 $nameSql";
} else {
	$sql = "TRUNCATE TABLE ".LABELS_TBL;
}

$db->_Execute($sql);

$sql = "INSERT INTO ". LABELS_TBL."
(
name1
,gis_data
)
SELECT 
name1
, ST.unionaggregate(st.transform(GIS_DATA,4326))
FROM ". BLOCKS_TBL."  WHERE name1 is not null and name1 <> '' $nameSql GROUP BY name1";
$db->_Execute($sql);

// Delete any labels that aren't assigned to any blocks
$sql = "DELETE FROM ". LABELS_TBL. " WHERE name1 NOT IN (SELECT DISTINCT name1 FROM ". BLOCKS_TBL . " WHERE name1 IS NOT NULL and name1!='')";
$db->_Execute($sql);


/* Update the x,y values in the label table for label placement */
$sql = "UPDATE ".LABELS_TBL. "
SET x = st.x(st.centroid(gis_data))
, y = st.y(st.centroid(gis_data)) WHERE 1=1 $nameSql";
$db->_Execute($sql);

$sql = "INSERT INTO nhRecreateLog (dateRun) values (getdate())";
$db->_Execute($sql);

echo json_encode(true); 
?>
